#!/bin/bash
set -e

# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
    echo "错误：请使用root用户执行此脚本" >&2
    exit 1
fi

# 判断是否已经安装docker
if command -v docker &> /dev/null; then
    echo "Docker已安装，跳过安装步骤"
else
    echo "===== 开始安装Docker ====="
    # 安装必要依赖
    echo "===== 安装依赖包 ====="
    yum install -y yum-utils device-mapper-persistent-data lvm2

    # 配置Docker镜像源（使用阿里云镜像源，加速下载）
    echo "===== 配置Docker镜像源 ====="
    yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

    # 更新yun软件包索引
    yum makecache

    # 安装Docker Engine
    echo "===== 安装Docker Engine ====="
    yum install -y docker-ce docker-ce-cli containerd.io --allowerasing

    mkdir -p /etc/docker

    # 配置Docker守护进程
    DOCKER_DAEMON_FILE="/etc/docker/daemon.json"
    # 定义需要的配置内容
    CONFIG_CONTENT=$(cat <<'EOF'
{
    "exec-opts": ["native.cgroupdriver=systemd"],
    "log-driver": "json-file",
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 5,
    "log-opts": {
        "max-size": "300m",
        "max-file": "2"
    },
    "registry-mirrors": ["https://jltw059v.mirror.aliyuncs.com"],
    "live-restore": true
}
EOF
)

    # 检查配置文件是否存在
    if [ -f "$DOCKER_DAEMON_FILE" ]; then
        echo "检测到已存在 daemon.json，跳过设置..."
    else
        echo "未找到 daemon.json，创建新配置文件..."
        # 写入配置内容
        echo "$CONFIG_CONTENT" > "$DOCKER_DAEMON_FILE"
        echo "配置文件 daemon.json 已创建"
    fi

    systemctl daemon-reload

    # 启动Docker并设置开机自启
    echo "===== 启动Docker服务 ====="
    systemctl start docker
    systemctl enable docker

    # 验证Docker安装
    echo "===== 验证Docker安装 ====="
    docker --version

fi

if command -v docker-compose &> /dev/null; then
    echo "Docker Compose已安装，跳过安装步骤"
else
    # 安装Docker Compose
    echo "===== 安装Docker Compose ====="
    curl -L "https://zbp-deploy.oss-cn-hangzhou.aliyuncs.com/00.%E8%BD%AF%E4%BB%B6/docker/docker-compose-linux-x86_64-2.39.2" -o /usr/local/bin/docker-compose

    # 设置执行权限
    chmod +x /usr/local/bin/docker-compose

    # 创建软链接，确保命令全局可用
    ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose 2>/dev/null || true

    # 验证Docker Compose安装
    echo "===== 验证Docker Compose安装 ====="
    docker-compose --version
fi

echo "===== 安装完成 ====="
echo "Docker和Docker Compose已成功安装"